package com.hk.Mgr.web.controller.app;

import com.hk.Mgr.web.message.StatusCode;
import com.hk.Mgr.web.message.order.OrderCommReq;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.ConstantLocation;
import com.hk.commons.ConstantProduct;
import com.hk.commons.ResultCode;
import com.hk.commons.StringHelper;
import com.hk.commons.entity.product.ProductInfo;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.vo.CheckInfo;
import com.hk.commons.vo.OrderActCheckMsg;
import com.hk.service.order.IOrderInfo;
import com.hk.service.product.IProductInfo;
import com.hk.service.sys.ISysUser;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = BaseCtrl.App)
public class AppOrderCtrl extends  BaseCtrl{
	private Logger logger = LoggerFactory.getLogger(AppOrderCtrl.class);

	@Autowired
	private IProductInfo prodService;

	@Autowired
	private ISysUser userService;

	//点击立即购买，进行下单前检查
	@RequestMapping(value = "/checkBuy", method = RequestMethod.POST)
	@ResponseBody
	public ResponseBase createOrder(@RequestBody OrderCommReq req, HttpServletRequest request) {
		ResponseBase<ResultMsg> resp = new ResponseBase<>();

		if(req == null || req.getUserId() == null || req.getProductId() == null||req.getBuyAmount() == null){
			resp.setResultCode(StatusCode.ERROR.key());
			resp.setMsg("参数错误");
			return resp;
		}

		Long userId = req.getUserId();

		Long productId = req.getProductId();

		BigDecimal buyAmount = req.getBuyAmount();

		Long userCardId = req.getUserCardId();


		String version = req.getV();
		if(StringUtils.isEmpty(version)){
			version = request.getParameter("v");
		}

		req.setV(version);

		ResultMsg resultMsg = checkCanBuy(req);

		try{
			if(!resultMsg.getCanBuy()){
				resp.setResult(resultMsg);
				resp.setResultCode(StatusCode.SUCCESS.key());
				resp.setMsg("下单校验失败");
				return resp;
			}

			//进行下单前常规数据检查
			CheckInfo checkInfo = prodService.checkBeforeCreateOrder(userId, productId, buyAmount, userCardId, version);
			logger.info("order checkBuy result ={}", checkInfo.toString());

			if(!checkInfo.getResult()){
				resultMsg = new ResultMsg(false, checkInfo.getResultMsg(), ConstantLocation.NONE);
				resp.setResult(resultMsg);
				resp.setResultCode(StatusCode.SUCCESS.key());
				resp.setMsg("下单校验失败");
				return resp;
			}

			OrderActCheckMsg orderActCheckMsg = new OrderActCheckMsg();
			orderActCheckMsg.setNeedPopMsg(false);

			//下单前活动数据校验
			orderActCheckMsg = prodService.checkAct(userId, productId, buyAmount);
			resultMsg.setOrderActCheckMsg(orderActCheckMsg);
			resp.setResult(resultMsg);
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setMsg("下单校验成功");
			return resp;
		}catch (Exception e){
			resultMsg = new ResultMsg(false, "下单检验失败", ConstantLocation.NONE);
			resp.setResult(resultMsg);
			resp.setResultCode(StatusCode.ERROR.key());
			resp.setMsg("下单校验失败");
		}
		return resp;
	}


	public  ResultMsg checkCanBuy (OrderCommReq req){

		ResultMsg resultMsg ;

		Long userId = req.getUserId();

		Long prodId = req.getProductId();

		String version =  req.getV();
		logger.info("user app version = {}", version);

		//检查用户是否绑卡
		SysUser user = userService.findById(userId);
		if( user == null || user.getCloseAccount() == 1){ //已销户不给购买-2.7.6
			resultMsg = new ResultMsg(false, "该用户不存在", ConstantLocation.NONE);
			return  resultMsg;
		}

		if(user.getHasVirtualAccount() != 1){
			resultMsg = new ResultMsg(false, "用户未绑卡", ConstantLocation.TIE_CARD);
			return  resultMsg;
		}

		//检查订单信息，如果通过检查再创建订单，否则不创建订单
		CheckInfo checkInfo = prodService.checkProdBuyVersion(version, "2.6.1", prodId, userId);
		logger.info("check version result = {}", checkInfo.toString());
		if (checkInfo.getResult() == false) {
			resultMsg = new ResultMsg(false, checkInfo.getResultMsg(), ConstantLocation.UPDATE_VERSION);
			return resultMsg;
		}

		checkInfo = prodService.checkProdBuyKyc(prodId, userId);
		if (checkInfo.getResult() == false) {
			logger.info("checkBeforeCreateOrder, user kyc not finished , can not by prod");
			resultMsg = new ResultMsg(false, checkInfo.getResultMsg(), ConstantLocation.DO_KYC);
			return resultMsg;
		}


		ProductInfo prod = prodService.findById(prodId);
		if (prod == null || prod.getParId() == null) {
			logger.info( "该产品不存在，或产品父标不存在");
			resultMsg = new ResultMsg(false, "该产品不存在，或产品父标不存在", ConstantLocation.NONE);
			return resultMsg;
		}

		//检查产品限购
		if (prod.getLimitNum() != null) {
			Long parId = prod.getParId();
			Integer buyNum = prodService.getBuyNum(userId, parId);
			if (buyNum >= prod.getLimitNum()) {
				String errorMsg =  "该产品限购" + prod.getLimitNum() + "笔， 您已购买" + buyNum + "笔，不能再次购买！";
				resultMsg = new ResultMsg(false, errorMsg, ConstantLocation.NONE);
				return resultMsg;
			}
		}

		//待售产品不允许购买
		if (prod.getWaitSale() == null || prod.getWaitSale() == ConstantProduct.PRODUCT_WAITSALE_TRUE) {
			logger.info("该产品未开售，此次购买失败！");
			resultMsg = new ResultMsg(false, "该产品未开售，此次购买失败！", ConstantLocation.NONE);
			return resultMsg;
		}

		//如果是加息收益产品
		if (prod.getSaleType() == ConstantProduct.PRODUCT_SALETYPE_04) {
			checkInfo = prodService.canBuy(userId);
			if (checkInfo.getResult() == false) {
				resultMsg = new ResultMsg(false, checkInfo.getResultMsg(), ConstantLocation.NONE);
				return resultMsg;
			}
		}

		resultMsg = new ResultMsg(true, "通过下单校验", ConstantLocation.NONE);
		return resultMsg;
	}

	private  class CanBuyMsg{
		public String errorMsg;

		public String newLocation;

		public String getErrorMsg() {
			return errorMsg;
		}

		public void setErrorMsg(String errorMsg) {
			this.errorMsg = errorMsg;
		}

		public String getNewLocation() {
			return newLocation;
		}

		public void setNewLocation(String newLocation) {
			this.newLocation = newLocation;
		}
	}

	private class  ResultMsg{
		public Boolean canBuy;

		public CanBuyMsg canBuyMsg = new CanBuyMsg();

		public OrderActCheckMsg orderActCheckMsg = new OrderActCheckMsg();


		public Boolean getCanBuy() {
			return canBuy;
		}

		public void setCanBuy(Boolean canBuy) {
			this.canBuy = canBuy;
		}

		public CanBuyMsg getCanBuyMsg() {
			return canBuyMsg;
		}

		public void setCanBuyMsg(CanBuyMsg canBuyMsg) {
			this.canBuyMsg = canBuyMsg;
		}

		public OrderActCheckMsg getOrderActCheckMsg() {
			return orderActCheckMsg;
		}

		public void setOrderActCheckMsg(OrderActCheckMsg orderActCheckMsg) {
			this.orderActCheckMsg = orderActCheckMsg;
		}


		public ResultMsg(Boolean canBuy, String  errorMsg, String newLocation) {
			this.canBuy = canBuy;
			this.getCanBuyMsg().setErrorMsg(errorMsg);
			this.getCanBuyMsg().setNewLocation(newLocation);
		}
	}
}
